package com.hengxinguotong.zhihuichengjian.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AddNoticedPersonAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.AddNoticedPersonAndMessageAdapter;
import com.hengxinguotong.zhihuichengjian.bean.AddGroupPersonnelListRes;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/3/11.
 */

public class SearchNoticedPersonActivity extends BaseActivity{
    @BindView(R.id.tv_title_name)
    HXTextView tvTitleName;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_tv)
    HXTextView saveTv;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.iv_p)
    ImageView ivP;
    @BindView(R.id.et_project)
    HXEditTextView etProject;
    @BindView(R.id.personnel_lv)
    PullToRefreshListView personnelLv;
    private static final int MSG_UPDATE_INFO = 0x110;
    private int pageIndex = 1;
    private AddNoticedPersonAdapter addPersonAdapter;
    private AddNoticedPersonAndMessageAdapter  addNoticedPersonAndMessageAdapter;
    private List<User> mUsers;
    private List<User> selectUsers, noticedPersons;
    private boolean isLive = false;
    private int type = 0;
    private int workType = -1;//工种，-1表示查询所有，0表示查询无工种，其他表示不同工种

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_INFO:
                    if (personnelLv != null) {
                        pageIndex = 1;
                        getPersonnelList(null);
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_personnel);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", 0);
        isLive = getIntent().getBooleanExtra("isLive", false);
        workType = getIntent().getIntExtra("workType", -1);
        noticedPersons = (List<User>) getIntent().getSerializableExtra("noticedPersons");
        if (selectUsers == null) {
            selectUsers = new ArrayList<User>();
            selectUsers.addAll(noticedPersons);
        }
        initView();
        addListener();
        getPersonnelList(getResources().getString(R.string.loading));
    }

    private void initView() {
        mUsers = new ArrayList<>();
        if(!isLive){
            addPersonAdapter = new AddNoticedPersonAdapter(mUsers, this);
            personnelLv.setAdapter(addPersonAdapter);
        }else {
            addNoticedPersonAndMessageAdapter = new AddNoticedPersonAndMessageAdapter(mUsers, this);
            personnelLv.setAdapter(addNoticedPersonAndMessageAdapter);
        }
    }

    private void addListener() {
        etProject.addTextChangedListener(searchTextWatcher);
        personnelLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                User user;
                if(!isLive){
                    user  = (User) addPersonAdapter.getItem(position - 1);
                }else {
                    user  = (User) addNoticedPersonAndMessageAdapter.getItem(position - 1);
                }
                if (user.isInUsers(selectUsers)) {
                    user.isInUsersRemoved(selectUsers);
                } else {
                    selectUsers.add(user);
                }
                if(!isLive){
                    addPersonAdapter.notifyDataSetChanged();
                }else {
                    addNoticedPersonAndMessageAdapter.notifyDataSetChanged();
                }
            }
        });

        personnelLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                getPersonnelList(null);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex++;
                getPersonnelList(null);
            }
        });
    }

    private void getPersonnelList(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("type", type);
            jsonObject.put("workType", workType);
            jsonObject.put("pageNum", pageIndex + "");
            jsonObject.put("name", etProject.getEditableText().toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/person/queryPersonList/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (personnelLv.isRefreshing()) {
                    personnelLv.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    AddGroupPersonnelListRes personnelListRes = gson.fromJson(json, AddGroupPersonnelListRes.class);
                    addData(personnelListRes.getValue());
                }
            }

            @Override
            public void onFailure(String json) {
                if (personnelLv.isRefreshing()) {
                    personnelLv.onRefreshComplete();
                }
            }
        });
    }

    private void addData(List<User> datas) {
        if (pageIndex == 1) {
            if(datas.size()==0){
                showEmptyView(personnelLv);
            }else{
                dismissEmptyView();
            }
            mUsers = datas;
            if (datas.size() == Utils.ONCECOUNT) {
                personnelLv.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
            }
        } else {
            mUsers.addAll(datas);
        }

        if(!isLive){
            addPersonAdapter.setDatas(mUsers);
        }else {
            addNoticedPersonAndMessageAdapter.setDatas(mUsers);
            filter();
        }

        if (datas.size() < Utils.ONCECOUNT) {
            personnelLv.setMode(PullToRefreshBase.Mode.DISABLED);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }

    private void filter(){
        for(User user:selectUsers){
            for(User mUser:mUsers){
                if(mUser.getUserId().equals(user.getUserId())){
                    mUser.setStatus(user.getStatus());
                }
            }
        }
        addNoticedPersonAndMessageAdapter.setDatas(mUsers);
    }

    @OnClick({R.id.iv_back, R.id.save_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_tv:
                Intent intent = getIntent();
                if (selectUsers.size() != 0) {
                    intent.putExtra("selectNoticers", (Serializable) selectUsers);
                    setResult(1, intent);
                }
                finish();
                break;
        }
    }


    private TextWatcher searchTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mHandler.removeMessages(MSG_UPDATE_INFO);
            mHandler.sendEmptyMessageDelayed(MSG_UPDATE_INFO, 500);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    public List<User> getSelectUsers() {
        return selectUsers;
    }

}
